package com.sinosoft.hbzyy.app.wms.base.data.endpoint.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;

import com.sinosoft.framework.core.api.domain.UserEntity;
import com.sinosoft.framework.core.common.constants.UserConstants;
import com.sinosoft.framework.core.common.exception.BusinessException;
import com.sinosoft.framework.core.common.utils.security.DigestUtil;
import com.sinosoft.framework.core.common.utils.security.EncodeUtil;
import com.sinosoft.framework.core.common.utils.string.StringUtil;
import com.sinosoft.framework.core.service.manager.OrganizationManager;
import com.sinosoft.framework.core.service.manager.RoleManager;
import com.sinosoft.framework.core.service.manager.UserManager;
import com.sinosoft.hbzyy.app.weedfs.api.WeedfsService;
import com.sinosoft.hbzyy.app.weedfs.model.RequestResult;
import com.sinosoft.hbzyy.app.wms.base.data.api.DoctorUserService;
import com.sinosoft.hbzyy.app.wms.base.data.endpoint.DoctorUserEndpoint;
import com.sinosoft.hbzyy.app.wms.base.data.model.DoctorUserEntity;
import com.sinosoft.hbzyy.framework.core.api.model.PageList;
import com.sinosoft.hbzyy.framework.util.ResultHelper;

public class DoctorUserEndpointImpl implements DoctorUserEndpoint {
	
	/**
	 * 初始密码
	 */
	public final String password="123456";
	
	/**
	 * 角色id
	 */
	public final String rid="598cc9d4-1d1d-414b-b90b-6a0ef149f57b";
	/**
	 * 盐长度
	 */
	private static final int SALT_SIZE = 8; 
	/**
	 *  加密算法
	 */
	public static final String HASH_ALGORITHM = "SHA-1"; 
	/**
	 *  随机盐生成函数中，遍历大小值
	 */
	public static final int HASH_INTERATIONS = 1024; 
	
	private DoctorUserService doctorUserService;
	
	private WeedfsService weedfsService;
	
	private OrganizationManager organizationManager;
	
    private UserManager userManager;
	
	private RoleManager roleManager;

	public void setWeedfsService(WeedfsService weedfsService) {
		this.weedfsService = weedfsService;
	}

	public OrganizationManager getOrganizationManager() {
		return organizationManager;
	}

	public void setOrganizationManager(OrganizationManager organizationManager) {
		this.organizationManager = organizationManager;
	}

	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public void setDoctorUserService(DoctorUserService doctorUserService) {
		this.doctorUserService = doctorUserService;
	}

	@Override
	public Map<String, Object> createDoctorUser(DoctorUserEntity doctor) {
		Message message = PhaseInterceptorChain.getCurrentMessage();
		HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);// 获取到request
		doctor.setCreateBy(Long.parseLong(request.getSession().getAttribute("username").toString()));
		// 创建湖北省中医院app后台管理人员信息
		String uid = UUID.randomUUID().toString();
		doctor.setId(uid);
		try {
			doctorUserService.createDoctorUser(doctor);
			List<com.sinosoft.framework.core.api.domain.OrganizationEntity> organEntity = organizationManager
					.retrieveOrganizationsByNameAndCode(null, doctor.getOrgCode());
			UserEntity userEntity = new UserEntity();
			// 给权限用户设置机构id
			userEntity.setOid(organEntity.get(0).getId());
			userEntity = doctorUserToPmsUser(doctor, userEntity);
			userEntity.setId(uid);
			// 没有密码,设置默认密码
			if (StringUtil.isBlank(userEntity.getPassword())) {
				userEntity.setPassword(UserConstants.USER_PASSWORD);
			}
			this.entryptPassword(userEntity);
			userManager.createUser(userEntity);
			String[] uids = { uid };
			roleManager.createRoleUserRef(rid, uids);
		} catch (BusinessException e) {
			//如果出现异常，直接删除app后台管理人员信息和人员科室关联信息,接着看pms人员是否插入如果插入直接删除，如果没有直接返回异常信息
			doctorUserService.deleteDoctorUserById(uid);
			UserEntity user = userManager.retrieveUserById(uid);
			if(user==null) {
				return ResultHelper.buildErrorResult("添加人员失败");
			}
			userManager.deleteUserById(uid);
			return ResultHelper.buildErrorResult("添加人员失败");
		}
		return ResultHelper.buildSuccessResult(doctor);
	}

	@Override
	public Map<String, Object> updateDoctorUser(DoctorUserEntity doctor) {
		Message message = PhaseInterceptorChain.getCurrentMessage();
		HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);// 获取到request
		doctor.setUpdateBy(Long.parseLong(request.getSession().getAttribute("username").toString()));
		return doctorUserService.updateDoctorUser(doctor);
	}

	@Override
	public Map<String, Object> updateDoctorTextAndVideo(Map<String, Object> map) {
		String id=map.get("id").toString();
		String isText=map.get("isText").toString();
		String isVideo=map.get("isVideo").toString();
		return doctorUserService.updateDoctorTextAndVideo(id, isText, isVideo);
	}

	@Override
	public Map<String,Object> retrieveDoctorUser(String id,String orgCode,String name,String deptCode,Integer currentPage,Integer rows) {
		 PageList<DoctorUserEntity> pageList = doctorUserService.retrieveDoctorUser(id,orgCode,name,deptCode, currentPage, rows);
		 return ResultHelper.buildSuccessResult(pageList);
	}
	
	/**
	 * 图片上传带保存信息
	 */
	@Override
	public Map<String, Object> uploadPicture(String pictureInfo, InputStream is) {
		byte[] buffer=new byte[1024];  
        int len=0;  
        ByteArrayOutputStream bos=null;
        try {
        	//定义一个jsonfactory
        	MappingJsonFactory factory = new MappingJsonFactory();
        	//解析固定的json格式的字符串
    		JsonParser parser = factory.createJsonParser(pictureInfo);
    		//将json字符串转换为相应的Entity
    		DoctorUserEntity user = parser.readValueAs(DoctorUserEntity.class);
			 bos=new ByteArrayOutputStream(); 
			while((len=is.read(buffer))!=-1){  
			    bos.write(buffer,0,len);  
			}  
			 bos.flush();  
			 bos.toByteArray();
			 RequestResult files = weedfsService.uploadFiles(bos.toByteArray());
			 user.setImageUrl(files.getFid());
			 doctorUserService.createDoctorUser(user);
			 return ResultHelper.buildSuccessResult(user);
		} catch (IOException e) {
			e.printStackTrace();
			return ResultHelper.buildErrorResult("图片上传失败"+e.getMessage());
		}finally {
			if(is==null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bos==null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 设置pms用户信息
	 * 
	 * @param doctorUserEntity
	 *            医生信息
	 * @param user
	 *            pms用户
	 * @return
	 */
	private UserEntity doctorUserToPmsUser(DoctorUserEntity doctorUserEntity,
			UserEntity user) {
		// 先给权限系统中用户信息设置值
		user.setName(doctorUserEntity.getName());
		user.setPassword(password);
		user.setUsername(doctorUserEntity.getTel());
		return user;
	}

	/**
	 * 密码加密 若盐不存在则生成随机的盐，并经过1024次 SHA1哈希。若盐存在则直接解码
	 * 
	 * @param userEntity
	 *            用户信息
	 */
	private void entryptPassword(UserEntity userEntity) {
		byte[] salt = null;
		if (!StringUtil.isBlank(userEntity.getSalt())) {
			salt = EncodeUtil.decodeHex(userEntity.getSalt());
		} else {
			salt = DigestUtil.generateSalt(SALT_SIZE);
			userEntity.setSalt(EncodeUtil.encodeHex(salt));
		}
		byte[] hashPassword = DigestUtil.sha1(userEntity.getPassword()
				.getBytes(), salt, HASH_INTERATIONS);
		userEntity.setPassword(EncodeUtil.encodeHex(hashPassword));
	}

	@Override
	public void retrieveAccidByDoctorCode(String doctorCode, HttpServletRequest request, HttpServletResponse response) {
		String accid = doctorUserService.retrieveAccidByDoctorCode(doctorCode);
		String callback = request.getParameter("callback");
/*		boolean success = false;
		if(!StringUtils.isBlank(accid)) {
			success= true;
		}
		String jsonData = "{\"success\":\"" + success + "\",\"accid\":" + accid+ "}";
		try (PrintWriter out = response.getWriter()) {
			out.println(callback+jsonData);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
	}

	@Override
	public Map<String, Object> retrieveAccidByDoctorCode(String doctorCode) {
		return doctorUserService.retrieveDoctorAccidByDoctorCode(doctorCode);
	}

	@Override
	public void retrieveAccidByCode(String doctorCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Map<String, Object> retrieveDoctorByPinYin(String namePy,int curpage,int pageSize) {
       return doctorUserService.retrieveDoctorByPinYin(namePy,curpage,pageSize);
	}

	@Override
	public Map<String, Object> retrieveAllDoctorByName(String name) {
		return doctorUserService.retrieveDoctorAllByName(name);
	}
}
